/***********************************************************************************************************************************
 * Name:	Tables_Update-Statistics-All.sql
 * Author:	Frank Figearo (frank@sqlnerd.me)
 * Summary:	Update statistics in all databases.
 */
SET IMPLICIT_TRANSACTIONS OFF;
DECLARE @tsql_command NVARCHAR(MAX);
DECLARE list CURSOR LOCAL FAST_FORWARD FOR
	SELECT tsql_command = REPLACE(N'USE [?]; EXECUTE sp_updatestats', '?', [name])
	  FROM sys.databases WHERE [state] = 0 AND database_id <> 2 ORDER BY database_id DESC;
OPEN list;
WHILE (0=0) BEGIN;
  FETCH NEXT FROM list INTO @tsql_command;
  IF @@FETCH_STATUS = 0 EXECUTE (@tsql_command) ELSE BREAK;
END;
CLOSE list;
DEALLOCATE list;